<script>
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'
import {
  loadEnergyConsumptionStructure,
} from '@/api/enterpriseQuarterlyReport'
import EnergyTableMixin from '@/components/quarterly-account-table/energy-table-mixin'
import ArrowSelectMixin from '@/components/quarterly-account-table/arrow-select-mixin'
import { selectEnergyDiscountList } from '@/api/energyDiscount'
import { uuid } from '@/utils'

import HeadEnergyConsumptionStructureTable from './head-energy-consumption-structure-table.vue'

const plus = (a, b) => {
  const isEmpty = x => x == null || x === ''
  if (isEmpty(a) || isEmpty(b)) return ''
  const n = +(((+a) + (+b)).toFixed(2))
  return Number.isFinite(n) ? n : ''
}
export default {
  name: 'energy-consumption-structure-table',
  mixins: [EnergyTableMixin, ArrowSelectMixin],
  components: {
    HeadEnergyConsumptionStructureTable
  },
  data () {
    return {
      // 表序号
      seriesNo: '表1-2',
    }
  },
  computed: {
    // 消费量中的“合计"
    calc () {
      const lists = this.lists.map(v => v.data)
      return lists.map(
        vv => {
          const t1 = vv.find(x => x.key === 'industrialProduction')
          const t2 = vv.find(x => x.key === 'nonIndustrialProduction')
          return plus(t1 && t1.value, t2 && t2.value)
        }
      )
    },
    summary () {
      const obj = {
        energyName: '能源合计',
        unitOfMeasurement: '',
        code: '40',
        referenceDiscountFactor: '',
      }
      // 第一行是”原煤“  原煤已填写，”其中“则不计入”能源合计“
      const has01 = this.calc[0] !== ''
      const lists = this.lists.filter(v => {
        const data = v.data
        // 是否是”其中“项所在行
        const isQizhong = data.some(vv => vv.key === 'code' && /02|03|04|05/.test(vv.value))
        return (has01 && !isQizhong) || !has01
      }).map(v => v.data)
      // console.log('hahha: ', lists)
      // 折标系数
      const sss = lists.map(v => {
        const target = v.find(vv => vv.key === 'useScalingFactor')
        return target ? target.value : ''
      })
      const props = this.flattenColumns.map(v => v.prop)
      const listsMap = props.reduce((acc, prop) => {
        if (!['referenceDiscountFactor', 'useScalingFactor'].includes(prop)) {
          acc[prop] = lists.map(v => {
            const target = v.find(vv => vv.key === prop)
            return target ? target.value : ''
          })
        }
        return acc
      }, {})
      // 消费量中的“合计"
      listsMap.total = [...this.calc]
      // ①期初库存合计=能源品种×采用折标系数（累加）；
      // ②实物量合计=上列数值累加；
      // ③金额合计=上列数值累加；
      // ④消费量：工业生产消费、用于原材料、非工业生产消费、合计中运输工具消费分别=能源品种×采用折标系数（累加）
      // 合计=工业生产消费累加值+非工业生产消费累计值；
      // ⑤期末库存合计=能源品种×采用折标系数（累加）。
      const accumulate = (prop, withFactor) => {
        const n = +(listsMap[prop].reduce((acc, v, i) => {
          const vvv = (Number.isFinite(+v) ? +v : 0) * (withFactor ? (+sss[i] || 1) : 1)
          // if (process.env.NODE_ENV === 'development' && prop === 'industrialProduction') {
          //   console.log(`${(Number.isFinite(+v) ? +v : 0)} x ${(withFactor ? (+sss[i] || 1) : 1)} = ${vvv}`)
          //   console.log(`${acc} + ${vvv} = ${acc + vvv}`)
          // }
          acc += vvv;
          return acc
        }, 0).toFixed(2))
        return Number.isFinite(n) ? n : ''
      }
      const getValue = (prop) => {
        if (
          [
            'beginningInventory', 'endingInventory',
            'industrialProduction',
            'forRawMaterials',
            'nonIndustrialProduction',
            'transportationConsumption',
            'physicalQuantity',
          ].includes(prop)
        ) {
          // 期初库存量、期末库存合计
          // 工业生产消费、用于原材料、非工业生产消费、合计中运输工具消费
          return accumulate(prop, true)
        } else if (
          ['amount'].includes(prop)
        ) {
          // 实物量、金额
          return accumulate(prop)
        } else if (
          prop === 'total'
        ) {
          return plus(
            getValue('industrialProduction'),
            getValue('nonIndustrialProduction')
          )
        }
      }
      const data = this.flattenColumns.map(v => {
        let editable = true
        if (
          Object.keys(obj).includes(v.prop)
        ) {
          editable = false
        }
        return {
          key: v.prop,
          value: obj[v.prop] || getValue(v.prop),
          editable,
        }
      })
      // console.log('hahah2: ', data)
      return {
        uuid: uuid(),
        data: data
      }
    },
  },
  created () {
    this.loadList = loadEnergyConsumptionStructure
  },
  methods: {
    getEnergyDiscount () {
      return selectEnergyDiscountList().then(res => {
        return res.data || []
      })
    },
    transfer (lists) {
      const props = this.flattenColumns.map(v => v.prop)
      return lists.map(v => {
        return {
          uuid: uuid(),
          informant: {
            personInCharge: v.personInCharge,
            informer: v.informer,
            telephone: v.telephone,
            fillInDate: v.fillInDate,
          },
          data: props.map(vv => {
            const editable = !this.readonly && !['energyName', 'unitOfMeasurement', 'code', 'total', 'referenceDiscountFactor'].includes(vv)
            return {
              key: vv,
              value: String(v[vv] || ''),
              editable,
              calculable: vv === 'total'
            }
          })
        }
      })
    },
    getCalc (row, prop, value) {
      const calc = this.calc
      if (prop === 'total') {
        return calc[row]
      }
      return value
    },
    // 初始化表数据
    initLists (params) {
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList(params).then(async res => {
          if (res.code === 200) {
            let data = res.data || []
            if (data.length === 0) {
              // 为空时加载默认能源名称
              const energyDiscount = await this.getEnergyDiscount()
              data = energyDiscount.map(
                /**
                 *
                 * @param v{{
                 *  id: string | number;
                 *  name: string;
                 *  discountFactorUnit: string;
                 *  referenceCoefficient: string;
                 * }}
                 * @returns {{unitOfMeasurement: (*|string), referenceDiscountFactor: (*|string), code: string, useScalingFactor: number, energyName: string}}
                 */
                v => ({
                  energyName: v.name || '',
                  unitOfMeasurement: v.discountFactorUnit ? (v.discountFactorUnit.split('/')[1]) : '吨标准煤',
                  useScalingFactor: Math.min(
                    ...(v.referenceCoefficient || '').split('-').map(vv => +vv)
                  ),
                  referenceDiscountFactor: v.referenceCoefficient || '',
                  code: String(v.id).padStart(2, '0'),
                })
              )
            } else {
              const findIndex = data.findIndex(v => v.energyName === '能源合计' || v.code === '40')
              if (findIndex > -1) {
                data.splice(findIndex, 1)
              }
            }
            this.lists = this.transfer(data)

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          console.log('reject')
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title" :series-no="seriesNo">
      <h2 class="table-title">
        {{title}}
      </h2>
    </slot>
    <div class="report-table-head">
      <HeadEnergyConsumptionStructureTable></HeadEnergyConsumptionStructureTable>
    </div>
    <el-scrollbar :style="{height: 'calc(100% - 156px)'}" wrap-style="overflow-x: hidden;">
      <table class="report-table">
        <tbody ref="tbody">
        <tr v-for="(item, i) in lists" :key="item.uuid">
          <th v-if="showLineNumber" class="readonly width-40px line-number">{{i + 1}}</th>
          <td
            v-for="(d, index) in item.data" :key="item.uuid + index"
            :class="{'is-calculable': d.calculable}"
          >
            <div v-if="!d.editable" class="span-cell">
              {{d.calculable ? calc[i] : d.value}}
            </div>
            <div v-else class="input-cell">
              <input type="text" v-model="d.value" @click="clickHandler">
            </div>
          </td>
        </tr>
        <tr class="readonly">
          <th v-if="showLineNumber" class="readonly width-40px line-number">{{lists.length + 1}}</th>
          <td v-for="(item, index) in summary.data" :key="summary.uuid + index">
            <div class="span-cell">
              {{item.value}}
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <report-person ref="reportPerson" :informer="informant"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．主要逻辑审核关系：</p>
          <p class="padding-horizontal">(1) 消费合计=工业生产消费+非工业生产消费。</p>
          <p class="padding-horizontal">(2) 工业生产消费≥用于原材料。</p>
          <p class="padding-horizontal">(3) 消费合计≥运输工具消费。</p>
          <p>2．企业只填写本企业消耗的有关能源品种数值。如本表未包括企业消耗的能源品种，企业应根据统计部门要求归并入相应能源品种内。</p>
          <p>3．能源合计=∑某种能源×某种能源折标准煤系数（不重复计算“其中”项）。</p>
          <p>4．综合能源消费量的计算方法：</p>
          <p class="padding-horizontal">(1)非能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-回收利用折标量合计（表1-2-1中第13列）。</p>
          <p class="padding-horizontal">(2)能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计（表1-2-1中第12列）-回收利用折标量合计（表1-2-1中第13列）。</p> -->
        </template>

        <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly autosize></el-input>
      </div>
    </el-scrollbar>
  </div>
</template>
